﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using AMG.Config;
using AMG.Model;
using AMG.Common;
using System.IO;

namespace AMG.Web.UI.Page
{
    public class BasePage:System .Web .UI.Page  
    {
        private long dur;

        protected const int PAGESZ = 20;
        /// <summary>
        /// 登录用户的令牌
        /// </summary>
        protected HttpCookie cookieToken;

        /// <summary>
        /// 当前登录用户ID
        /// </summary>
        protected int UserID;

        /// <summary>
        /// 当前登录用户姓名
        /// </summary>
        protected string UserName;

        protected string backurl;
        /// 构造函数
        /// </summary>
        public BasePage()
        {
            this.Load += new EventHandler(BasePage_Load);
            this.LoadComplete += new EventHandler(BasePage_LoadComplete);
            //this.LoadComplete += new EventHandler(UserPage_LoadComplete);
        }

        protected string getbackurl()
        {
            string url = "";
            //url = Request.ServerVariables["RawUrl"];
            url = Request.RawUrl;
            return url;
        }

        private void BasePage_LoadComplete(object sender, EventArgs e)
        {
            try
            {
                this.Page.Title = this.Page.Title + "|" + UiConfig.PageTitle;
            }
            catch
            {
                System.Web.UI.HtmlControls.HtmlGenericControl control = (System.Web.UI.HtmlControls.HtmlGenericControl)this.FindControl("pagetitle");
                if (control != null)
                {
                    try
                    {
                        control.InnerText = control.InnerText + "|" + UiConfig.PageTitle;
                    }
                    catch { }
                }
            }
        }

        /// <summary>
        /// LOAD事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BasePage_Load(object sender, EventArgs e)
        {
            dur = DateTime.Now.Ticks;
        }

        /// <summary>
        /// 退出
        /// </summary>
        protected virtual void Logout()
        {
            Context.Session.Remove("SITEINFO");
        }

        /// <summary>
        /// 检查是否登录
        /// </summary>
        protected virtual void CheckLogin()
        { }

        /// <summary>
        /// 登录状态处理
        /// </summary>
        /// <param name="state"></param>
        protected void CheckResultShow(EnumLoginState loginState, string backUrl)
        {
            string ErrorMsg = string.Empty;
            switch (loginState)
            {
                case EnumLoginState.Err_IPLimited:
                    ErrorMsg = "您的IP[" + AMG.Common.Public.GetClientIP() + "]被限制，不能登陆！";
                    break;
                case EnumLoginState.Err_Locked:
                    ErrorMsg = "您已经被锁定！";
                    break;
                case EnumLoginState.Err_UnActivation:
                    ErrorMsg = "您还没通过电子邮件激活，不能登陆本系统！";
                    break;
                case EnumLoginState.Err_TimeOut:
                    Context.Response.Redirect(backUrl);
                    break;
                case EnumLoginState.Err_NoAuthority:
                    ErrorMsg = "您没有此项的操作权限！";
                    break;
                case EnumLoginState.Err_DbException:
                    ErrorMsg = "系统错误。出错原因可能是：1.与数据库服务器的通信失败；2.数据库连接字符串不正确；3.数据库发生异常。";
                    break;
                case EnumLoginState.Err_DurativeLogError:
                    ErrorMsg = "连续错误登陆，您已经被锁定！";
                    break;
                case EnumLoginState.Err_NameOrPwdError:
                    ErrorMsg = "用户名不存在或者密码错误";
                    break;
                case EnumLoginState.Err_GroupExpire:
                    ErrorMsg = "您的帐号已过期";
                    break;
                case EnumLoginState.Err_NotAdmin:
                    ErrorMsg = "抱歉，您不是管理员。您的操作已经记录！<li>您的IP：[" + AMG.Common.Public.GetClientIP() + "]已被记录</li>";
                    break;
                case EnumLoginState.Succeed:
                    return;
                default:
                    ErrorMsg = "异常错误：" + loginState.ToString();
                    break;
            }
        }

        /// <summary>
        /// 显示错误信息,并中止执行
        /// </summary>
        /// <param name="ErrInfo">错误提示信息</param>
        /// <param name="DivID">容器编号</param>
        protected void ShowErr(string ErrInfo, HtmlContainerControl DivID)
        {
            DivID.Style.Value = "display:";
            DivID.InnerHtml = ErrInfo;
        }

        /// <summary>
        /// 显示操作成功信息
        /// </summary>
        /// <param name="SccInfo">成功提示信息</param>
        /// <param name="DivID">容器编号</param>
        protected void ShowSuc(string SucInfo, HtmlContainerControl DivID)
        {
            DivID.Style.Value = "display:";
            DivID.InnerHtml = SucInfo;
        }

        /// <summary>
        /// 验证COOKIE是否过期
        /// </summary>
        /// <returns></returns>
        protected bool Expired()
        {
            HttpCookie cookieToken = Context.Request.Cookies["AMGCookie"];
            int UserID = 0;
            if (cookieToken == null || cookieToken["token"] == null)
                return true;
            cookieToken.Domain = UiConfig.CookieDomain;
            string userCookie = cookieToken["token"];
            string desstr = AMG.Common.DES.Decrypt(userCookie, SecretConfig.UserKey, SecretConfig.UserIV);
            string[] userInfo = desstr.Split(SecretConfig.UserSeparator);
            EnumLoginState state = EnumLoginState.Err_TimeOut;
            if (userInfo.Length == 3)
            {
                UserID = int.Parse(userInfo[0]);
                string pass = userInfo[1];
                string cookip = userInfo[2];
                if (cookip != Public.GetClientIP())
                {
                    state = EnumLoginState.Err_TimeOut;
                }
                else
                {
                    AMG.BLL.User.User us = new AMG.BLL.User.User();
                    state = us.CheckLogin(UserID, pass);
                }
            }
            if (state == EnumLoginState.Succeed)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 取得当前登陆的用户ID
        /// </summary>
        /// <returns></returns>
        static public int GetCurrentUserID()
        {
            int UserID = 0;
            HttpCookie cookieToken = HttpContext.Current.Request.Cookies["AMGCookie"];
            if (cookieToken == null || cookieToken["token"] == null || cookieToken["token"] == "")
                return UserID;
            string userCookie = cookieToken["token"];
            string desstr = AMG.Common.DES.Decrypt(userCookie, SecretConfig.UserKey, SecretConfig.UserIV);
            string[] userInfo = desstr.Split(SecretConfig.UserSeparator);
            EnumLoginState state = EnumLoginState.Err_TimeOut;
            if (userInfo.Length == 3)
            {
                UserID = int.Parse(userInfo[0]);
                string pass = userInfo[1];
                AMG.BLL.User.User us = new AMG.BLL.User.User();
                state = us.CheckLogin(UserID, userInfo[1]);
            }
            if (state == EnumLoginState.Succeed)
            {
                return UserID;
            }
            else
            {
                return 0;
            }
        }
        /// <summary>
        /// 取得当前登陆的用户ID
        /// </summary>
        /// <returns></returns>
        public int GetUserID()
        {
            return GetCurrentUserID();
        }
    }
}
